# -*- coding: utf-8 -*-
# @Date   : 2020/3/20
# @File   : R42_TX_EntTaxCreditRatingCheck_CF.py
# @Author : zhaochen

'''eof
name:企业纳税纳税信用等级校验
code:R42_TX_EntTaxCreditRatingCheck_CF
tableName:
columnName:
groups:场景业务校验-税务
dependencies:TX_CQ_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''



import re
import sys
import datetime
import pandas as pd
import math




reload(sys)
sys.setdefaultencoding('utf-8')



def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = TX_CQ_DSJ["data"].get(table_Name)
        return data if isinstance(data, list) and len(data) > 0 else [{}]

    except:
        return [{}]


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """
    data_value = str(data_value)
    return_data = None
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data


def R42_TX_EntTaxCreditRatingCheck_CF(CcrDate=None):
    """
    企业税务信用等级需在C级（含）以上，不包括M级的企业通过，否则拒绝。
    根据申请月份：
    A、如果申请月份>5,取“当前年度-1”和“当前年度-2”,两年评级均大于等于C级才允许通过，否则拒绝。
    B、如果申请月份<=5,优先去取“当前年度-1”和“当前年度-2”，计算方法同上一条；
    如“当前年度-1”无数据，则取“当前年度-2”和“当前年度-3”，此时两年评级均大于等于C级才允许通过，否则拒绝。

    :param CcrDate: 测试时间，默认为None，
    :return:
    """

    if CcrDate is None:
        CcrMonth = datetime.datetime.now().month
        CcrYear = datetime.datetime.now().year
    else:
        # 用于分析
        CcrDate = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date()
        CcrMonth = CcrDate.month
        CcrYear = CcrDate.year

    syptSwpjxx = formatData('syptSwpjxx')

    if syptSwpjxx == [{}]:
        return u'缺失值'
    else:
        syptSwpjxx = pd.DataFrame(syptSwpjxx).dropna()
        if CcrMonth > 5:
            if str(CcrYear-1) in list(syptSwpjxx['SWXYPJSJ']):
                SWXYPJSJLastOne = convertDataType(syptSwpjxx[syptSwpjxx['SWXYPJSJ'] == str(CcrYear-1)]['SWXYPJ'].iloc[-1], 'str')
            else:
                SWXYPJSJLastOne = None

        else:
            if str(CcrYear-1) in list(syptSwpjxx['SWXYPJSJ']):

                SWXYPJSJLastOne = convertDataType(syptSwpjxx[syptSwpjxx['SWXYPJSJ'] == str(CcrYear - 1)]['SWXYPJ'].iloc[-1], 'str')

            else:
                if str(CcrYear-2) in list(syptSwpjxx['SWXYPJSJ']):
                    SWXYPJSJLastOne = convertDataType(syptSwpjxx[syptSwpjxx['SWXYPJSJ'] == str(CcrYear - 2)]['SWXYPJ'].iloc[-1], 'str')
                else:
                    SWXYPJSJLastOne = None


        # 纳税等级校验
        return SWXYPJSJLastOne


result = R42_TX_EntTaxCreditRatingCheck_CF()